<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 返回首页 -->
      <div class="back-home">
        <el-button type="text" @click="goHome">
          <iconify-icon icon="mdi:arrow-left" width="20" height="20"></iconify-icon>
          返回首页
        </el-button>
      </div>

      <div class="login-header">
        <h2>用户登录</h2>
        <p>User Login</p>
      </div>

      <!-- 用户类型选择 -->
      <div class="user-type-selection">
        <h3>选择用户类型</h3>
        <div class="user-type-grid">
          <div
            v-for="userType in userTypes"
            :key="userType.type"
            :class="['user-type-card', { active: selectedType === userType.type }]"
            @click="selectUserType(userType.type)"
          >
            <iconify-icon :icon="userType.icon" width="32" height="32" :style="{ color: userType.color }"></iconify-icon>
            <span>{{ userType.name }}</span>
          </div>
        </div>
      </div>

      <!-- 登录表单 -->
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            :placeholder="getUsernamePlaceholder()"
            prefix-icon="User"
            size="large"
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            size="large"
            show-password
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item>
          <div class="login-options">
            <el-checkbox v-model="loginForm.remember">
              记住我
            </el-checkbox>
            <el-link type="primary" :underline="false" @click="handleForgotPassword">
              忘记密码？
            </el-link>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-button"
            :loading="loading"
            :disabled="!selectedType"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 注册和忘记密码 -->
      <div class="register-section">
        <p class="register-text">
          还没有账号？
          <el-link type="primary" :underline="false" @click="handleRegister">
            立即注册
          </el-link>
        </p>
      </div>

      <!-- 测试账号提示 -->
      <div class="login-tips" v-if="selectedType">
        <p>测试账号：</p>
        <div v-for="account in getTestAccounts()" :key="account.type">
          <p>{{ account.name }} - {{ account.username }} / {{ account.password }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'

export default {
  name: 'LoginPage',
  setup() {
    const router = useRouter()
    const authStore = useAuthStore()

    // 表单引用
    const loginFormRef = ref(null)
    const loading = ref(false)
    const selectedType = ref('')

    // 用户类型配置
    const userTypes = [
      { type: 'player', name: '运动员', icon: 'mdi:run', color: '#3b82f6' },
      { type: 'volunteer', name: '志愿者', icon: 'mdi:account-student', color: '#2563eb' },
      { type: 'teacher', name: '教师', icon: 'mdi:account-tie', color: '#f97316' },
      { type: 'referee', name: '裁判', icon: 'mdi:whistle', color: '#22c55e' },
      { type: 'admin', name: '管理员', icon: 'mdi:shield-account', color: '#ef4444' }
    ]

    // 测试账号配置
    const testAccounts = {
      player: [
        { name: '学生账号', username: 'student1', password: '123456' }
      ],
      volunteer: [
        { name: '志愿者账号', username: 'volunteer1', password: '123456' }
      ],
      teacher: [
        { name: '教师账号', username: 'teacher1', password: '123456' }
      ],
      referee: [
        { name: '裁判账号', username: 'referee1', password: '123456' }
      ],
      admin: [
        { name: '管理员账号', username: 'admin', password: '123456' }
      ]
    }

    // 登录表单数据
    const loginForm = reactive({
      username: '',
      password: '',
      remember: false
    })

    // 表单验证规则
    const loginRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ]
    }

    // 选择用户类型
    const selectUserType = (type) => {
      selectedType.value = type
      // 清空表单
      loginForm.username = ''
      loginForm.password = ''
    }

    // 获取用户名占位符
    const getUsernamePlaceholder = () => {
      if (!selectedType.value) return '请先选择用户类型'
      const typeConfig = userTypes.find(t => t.type === selectedType.value)
      return `请输入${typeConfig?.name || '用户'}用户名`
    }

    // 获取测试账号
    const getTestAccounts = () => {
      return testAccounts[selectedType.value] || []
    }

    // 处理登录
    const handleLogin = async () => {
      if (!selectedType.value) {
        ElMessage.warning('请先选择用户类型')
        return
      }

      if (!loginFormRef.value) return

      try {
        // 表单验证
        await loginFormRef.value.validate()

        loading.value = true

        // 使用Pinia store进行登录
        await authStore.login({
          username: loginForm.username,
          password: loginForm.password,
          remember: loginForm.remember
        })

        ElMessage.success('登录成功')

        // 根据用户类型跳转到不同页面
        const routeMap = {
          admin: '/admin',
          teacher: '/teacher',
          referee: '/referee',
          player: '/user',
          volunteer: '/user'
        }

        const targetRoute = routeMap[selectedType.value] || '/user'
        router.push(targetRoute)

      } catch (error) {
        console.error('登录失败:', error)

        // 根据错误信息类型提供更精准的提示
        let errorMessage = '登录失败'
        if (error.message && error.message.includes('用户名或密码错误')) {
          errorMessage = '用户名或密码错误，请重新输入'
        } else if (error.message && error.message.includes('网络')) {
          errorMessage = '网络连接失败，请检查网络设置'
        } else {
          errorMessage = '登录失败，请检查用户名密码或网络连接'
        }

        ElMessage.error(errorMessage)
      } finally {
        loading.value = false
      }
    }

    // 返回首页
    const goHome = () => {
      router.push('/')
    }

    // 处理忘记密码
    const handleForgotPassword = () => {
      router.push('/forgot-password')
    }

    // 处理注册
    const handleRegister = () => {
      router.push('/register')
    }

    return {
      loginFormRef,
      loginForm,
      loginRules,
      loading,
      selectedType,
      userTypes,
      selectUserType,
      getUsernamePlaceholder,
      getTestAccounts,
      handleLogin,
      goHome,
      handleForgotPassword,
      handleRegister
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-box {
  background: white;
  border-radius: 16px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 450px;
  backdrop-filter: blur(10px);
  position: relative;
}

.back-home {
  position: absolute;
  top: 20px;
  left: 20px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
  margin-top: 20px;
}

.login-header h2 {
  color: #333;
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 8px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.login-header p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.user-type-selection {
  margin-bottom: 30px;
}

.user-type-selection h3 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
  font-size: 16px;
  font-weight: 500;
}

.user-type-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
  gap: 12px;
}

.user-type-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px 10px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f9fafb;
}

.user-type-card:hover {
  border-color: #667eea;
  background: #f3f4f6;
  transform: translateY(-2px);
}

.user-type-card.active {
  border-color: #667eea;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

.user-type-card span {
  margin-top: 8px;
  font-size: 12px;
  color: #374151;
  font-weight: 500;
}

.login-form {
  margin-bottom: 20px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.login-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  border: none;
  transition: all 0.3s ease;
}

.login-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.login-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.login-tips {
  margin-top: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  font-size: 12px;
  color: #666;
  line-height: 1.6;
}

.login-tips p {
  margin: 2px 0;
}

.login-tips p:first-child {
  font-weight: 600;
  color: #333;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  padding: 0 15px;
  box-shadow: 0 0 0 1px #e4e7ed inset;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #667eea inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #667eea inset;
}

:deep(.el-form-item__error) {
  font-size: 12px;
  color: #f56c6c;
}

.register-section {
  text-align: center;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #e5e7eb;
}

.register-text {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.register-text .el-link {
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-box {
    padding: 30px 20px;
  }

  .login-header h2 {
    font-size: 24px;
  }

  .user-type-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>